<script setup lang="ts">
// 编辑新增弹窗
import { computed, onMounted, ref, watch } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { useDialog } from 'naive-ui';
import { successMessage } from '@/utils/utils';
import {
  getLabelTreeAction,
  labelBindingCustomizeInsertAction,
  labelBindingInsertAction,
  labelBindingUpdateAction,
  msgCheckAction
} from '@/service/api';
import { localStg } from '@/utils/storage';

interface Props {
  show: boolean;
  logId?: number;
  type?: number; // 0.编辑；1.新增；2.新增自选
  analysisId?: number;
  labelObj?: any; // 标签对象
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  type: 0
});

interface FormData {
  selectedLabel: number | undefined;
  labelName: string;
}

const formData = ref<FormData>({
  selectedLabel: undefined,
  labelName: ''
});

const formRef = ref<FormInst | null>(null);

// 校验规则
const rules: FormRules = {
  selectedLabel: {
    type: 'number',
    required: true,
    message: '请选择标签',
    trigger: ['blur', 'change']
  },
  labelName: {
    required: true,
    message: '请输入标签名称',
    trigger: ['blur', 'input']
  }
};

const buttonList = ref<any[]>([
  {
    id: 1,
    text: '+添加已有标签'
  },
  {
    id: 2,
    text: '+添加自定义标签'
  }
]);

const currentBtn = ref<number>(1);

const emit = defineEmits(['update:show', 'refresh']);

const modalShowValue = computed({
  get() {
    return props.show;
  },
  set(value: boolean) {
    emit('update:show', value);
  }
});

watch(
  () => props.show,
  value => {
    if (value) {
      if (props.type === 0) {
        console.log('props.labelObj: ', props.labelObj);
        if (props.labelObj.type === 0) {
          currentBtn.value = 2;
          formData.value.labelName = props.labelObj.labelName;
        } else {
          currentBtn.value = 1;
          formData.value.selectedLabel = Number.parseInt(props.labelObj.labelId, 10);
        }
      }
    } else {
      currentBtn.value = 1;
      formData.value.selectedLabel = undefined;
      formData.value.labelName = '';
    }
  }
);

onMounted(() => {
  getLabelTreeDataAction();
});

const labelList = ref<any[]>([]);

// 获取标签树数据
async function getLabelTreeDataAction() {
  const { data, error } = await getLabelTreeAction({});
  if (!error) {
    labelList.value = data;
  }
}

// 取消
function closeModal() {
  modalShowValue.value = false;
}

const selectLabelName = ref<string>('');

// 标签选中
function labelSelectChange(value: string | number, option: any) {
  // console.log('value: ', value, option.labelName);
  selectLabelName.value = option.labelName;
}

const dialog = useDialog();

// 确认
function submitClick() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      // 手动输入标签需要校验敏感词
      if (currentBtn.value === 2) {
        const checkParams: any = {
          moduleValue: localStg.get('moduleId') || 1,
          keyword: formData.value.labelName
        };

        const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
        if (!checkError) {
          if (checkData && checkData.length > 0) {
            dialog.error({
              title: '温馨提示',
              content: `标签名称中包含以下敏感词：\n${checkData.join('，')}`,
              style: 'white-space: pre-line;',
              positiveText: '确认'
            });
            return;
          }
        }
      }

      if (props.type === 0) {
        // 编辑
        const params: any = {
          logId: props.logId,
          color: 4, // 手动编辑
          id: props.labelObj.id, // 主键id
          labelId: currentBtn.value === 1 ? formData.value.selectedLabel : props.labelObj.labelId,
          analysisId: props.analysisId,
          labelName: currentBtn.value === 1 ? selectLabelName.value : formData.value.labelName,
          type: currentBtn.value // 类别
        };
        const { data, error } = await labelBindingUpdateAction(params);
        if (!error) {
          successMessage('标签更新成功！');
          emit('refresh');
          closeModal();
        }
      } else if (props.type === 1) {
        // 新增
        const params: any = {
          logId: props.logId,
          color: 5, // 手动添加
          labelId: currentBtn.value === 1 ? formData.value.selectedLabel : null, // 标签id,新增自定义标签时可为null
          analysisId: props.analysisId, // 内容id
          labelName: currentBtn.value === 1 ? selectLabelName.value : formData.value.labelName, // 标签名称，不为自定义标签时可以为空
          type: currentBtn.value // 不能为空，正常标签 1 ，自定义标签2
        };
        const { data, error } = await labelBindingInsertAction(params);
        if (!error) {
          successMessage('标签新增成功！');
          emit('refresh');
          closeModal();
        }
      } else {
        // 自选新增
        const params: any = {
          logId: props.logId,
          color: 5, // 手动添加
          type: props.labelObj.type,
          sentence: props.labelObj.sentence,
          labelId: currentBtn.value === 1 ? formData.value.selectedLabel : null, // 标签id,新增自定义标签时可为null
          labelName: currentBtn.value === 1 ? selectLabelName.value : formData.value.labelName, // 标签名称，不为自定义标签时可以为空
          labelType: currentBtn.value // 不能为空，正常标签 1 ，自定义标签2
        };
        const { data, error } = await labelBindingCustomizeInsertAction(params);
        if (!error) {
          successMessage('标签新增成功！');
          emit('refresh');
          closeModal();
        }
      }
    }
  });
}
</script>

<template>
  <NModal
    v-model:show="modalShowValue"
    preset="card"
    :title="type === 0 ? '编辑标签' : '新增标签'"
    class="w-885px"
    :mask-closable="false"
    @close="closeModal"
  >
    <NSpace v-if="type !== 0" class="mb-20px">
      <NRadioGroup v-model:value="currentBtn" name="titleRadioGroup">
        <NRadioButton v-for="item in buttonList" :key="item.id" :value="item.id" :label="item.text"></NRadioButton>
      </NRadioGroup>
    </NSpace>
    <NForm ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="auto">
      <NFormItem v-if="currentBtn === 1" path="selectedLabel">
        <NCascader
          v-model:value="formData.selectedLabel"
          placeholder="招标文件标签库"
          :options="labelList"
          check-strategy="child"
          :show-path="false"
          :filterable="true"
          label-field="labelName"
          value-field="id"
          children-field="childList"
          :theme-overrides="{ columnWidth: '280px' }"
          @update:value="labelSelectChange"
        />
      </NFormItem>
      <NFormItem v-else path="labelName">
        <NInput v-model:value="formData.labelName" type="text" :maxlength="50" clearable />
      </NFormItem>
    </NForm>
    <template #footer>
      <NSpace class="w-full" :size="24" justify="end">
        <NButton class="w-72px" @click="closeModal">取消</NButton>
        <NButton class="w-72px" type="primary" @click="submitClick">确定</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped lang="scss">
.n-radio-group n-radio-group--button-group {
  height: 35px;
}
:deep(.n-radio-group__splitor--checked) {
  height: 35px !important;
  background-color: #836fff;
}
:deep(.n-radio-group__splitor) {
  height: 35px !important;
}
.n-radio-group .n-radio-button {
  height: 35px;
  font-weight: 400;
  font-size: 15px;
  color: #836fff;
  line-height: 31px;
  border: 2px solid #836fff;
}
.n-radio-group .n-radio-button.n-radio-button--checked {
  background: #836fff;
}
.n-radio-button--checked {
  color: #ffffff !important;
}
</style>
